const config = require('../config/index.js').default;
const authUtils = require('../utils/auth.js');

const { baseUrl: configBaseUrl } = config;
const baseUrl = configBaseUrl;

function request(url, method = 'GET', data = {}, options = {}) {
  const { 
    showLoading = false, 
    loadingText = '加载中...', 
    timeout = 10000,
    retryCount = 0,
    showError = true 
  } = options;
  
  // 显示加载提示
  if (showLoading) {
    wx.showLoading({
      title: loadingText,
      mask: true
    });
  }
  
  const header = {
    'content-type': 'application/json',
  };
  
  // 获取token，有就丢进请求头
  const tokenString = wx.getStorageSync('access_token');
  if (tokenString && tokenString.trim() !== '') {
    header.Authorization = `Bearer ${tokenString}`;
  }
  
  return new Promise((resolve, reject) => {
    // 设置超时定时器
    const timeoutId = setTimeout(() => {
      if (showLoading) wx.hideLoading();
      reject({ 
        code: 'TIMEOUT', 
        message: '请求超时，请检查网络连接',
        isTimeout: true 
      });
    }, timeout);
    wx.request({
      url: baseUrl + url,
      method,
      data,
      dataType: 'json', // 微信官方文档中介绍会对数据进行一次JSON.parse
      header,
      success(res) {
        clearTimeout(timeoutId);
        if (showLoading) wx.hideLoading();
        
        // 处理响应数据
        const responseData = res.data || res;
        
        // 检查HTTP状态码和业务状态码
        if (res.statusCode === 200 && responseData && responseData.code === 200) {
          resolve(responseData);
        } else if (res.statusCode === 401) {
          // 401未授权，可能是JWT令牌过期或无效
          authUtils.clearLoginInfo();
          authUtils.redirectToLogin();
          
          reject({ 
            code: 401, 
            message: '认证失败，请重新登录',
            needLogin: true 
          });
        } else {
          const errorMsg = responseData?.message || '请求失败，请重试';
          if (showError) {
            wx.showToast({
              title: errorMsg,
              icon: 'none',
              duration: 2000
            });
          }
          reject(responseData || { 
            code: res.statusCode, 
            message: errorMsg 
          });
        }
      },
      fail(err) {
        clearTimeout(timeoutId);
        if (showLoading) wx.hideLoading();
        
        // 网络错误处理
        let errorMessage = '网络异常，请检查网络连接';
        if (err.errMsg) {
          if (err.errMsg.includes('timeout')) {
            errorMessage = '请求超时，请重试';
          } else if (err.errMsg.includes('fail')) {
            errorMessage = '网络连接失败，请检查网络';
          }
        }
        
        if (showError) {
          wx.showToast({
            title: errorMessage,
            icon: 'none',
            duration: 2000
          });
        }
        
        reject({
          ...err,
          message: errorMessage,
          isNetworkError: true
        });
      },
    });
  });
}

// 导出请求和服务地址
module.exports = { default: request };
